package sv.net;

/**
 * NetworkIO implements a simply client and server functionality.
 * 
 * @author schneider.pj
 *
 */
public abstract class NetworkIO {

	/* commands used by the network interface */
	public final static int MSG_RECEIVED		=	1;
	public final static int READY				=   2;
	public final static int SHOOT				= 	3;
	public final static int HIT_SHIP			=	4;
	public final static int SHIP_DESTROYED		=	5;
	public final static int HIT_WATER			=	6;
	public final static int IM_A_LOSER_BABY		=	7;

	public final static int port = 2312;	
	private boolean clientMode = false; 
	
	private NetworkIOServer server;
	private NetworkIOClient client;
	
	
	/**
	 * initializes the connection as a server
	 */
	public void startServer() {
		server = new NetworkIOServer(this);
		server.start();
	}
	
	public void stopServer() {
		server.running = false;
	}

	
	// client-methods
	public int connectTo(String pHost) {
		this.clientMode = true;
		client = new NetworkIOClient(this);
		return client.connect(pHost);
	}
	
	
	public void disconnect() {
		client.disconnect();
		clientMode = false;
	}
	

	
	/**
	 * act as a client and send via known host name and port
	 * @returns answer from the server
	 * @param command
	 * @param field
	 */
	public synchronized int send(int command, int field) {
		System.out.println("send: " + command + ", " + field);
		if (clientMode) {
			return client.send(command, field);
		} else {
			return server.send(command, field);
		}
	}
	

	/**
	 * messageReceived() is called whenever a message is received
	 * @param message
	 */
	public abstract void messageReceived(int command, int field);
	
	void message(int command, int field) {
		System.out.println("received: " + command + ", " + field + " (time: "+System.currentTimeMillis() + ")");
		this.messageReceived(command,field);
	}
	
}
